package com.example.module_home.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.lib_mvi.base.BaseMVIFragment
import com.example.module_home.databinding.FragmentHomeBinding
import com.example.module_home.home.intent.SimpleTypeIntent
import com.example.module_home.home.state.SimpleTypeState
import com.example.module_home.home.viewmodel.HomeViewModel
import kotlinx.coroutines.launch

/**
 * @author yaotianxue
 * @description
 * @date 2025/2/25
 */
class HomeFragment:BaseMVIFragment() {
    private lateinit var homeViewModel: HomeViewModel
    private val binding: FragmentHomeBinding by lazy {
        FragmentHomeBinding.inflate(layoutInflater)
    }
    override fun generateViewModel() {
        homeViewModel = ViewModelProvider(this)[HomeViewModel::class.java]
    }

    override fun lazyLoad() {

    }

    override fun initData() {
        super.initData()
        //1:发送意图
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                homeViewModel.intents.send(SimpleTypeIntent.getSimpleType)
            }
        }
    }
    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return binding.root
    }

    override fun handleState() {
        //2:订阅流
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
               homeViewModel.simpleTypeFlow_.collect{
                   when(it){
                       is SimpleTypeState.SimpleTypeSuccess->{
                            showMsg("成功 ${it.list}")
                       }
                       is SimpleTypeState.Failed->{
                           showMsg("失败 ${it.msg}")

                       }
                       is SimpleTypeState.Init->{
                           showMsg("加载中。。。。 ")

                       }
                       is SimpleTypeState.Empty->{
                           showMsg("空。。。。 ")

                       }
                   }
               }
            }
        }

        //新协程订阅其他流
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){

            }
        }
    }
}